﻿using Pay.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Pay.DTO;
using Pay.TO;
using Pay.Token.Utils;
using Pay.Core;
using System.Threading.Tasks;
using Autofac;

namespace Pay.Token.Controllers {
    /// <summary>
    /// 会员空间
    /// </summary>
    [AppAuthorize("Member")]
    public class MemberSpaceController : GeneralController {
        private ISettingService _iSettingService;
        private ITokenGradeService _iTokenGradeService;
        private IMerchantService _iMerchantService;
        private IComponentContext _iComponentContext;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iSettingService"></param>
        /// <param name="iTokenGradeService"></param>
        /// <param name="iMerchantService"></param>
        /// <param name="icomponentContext"></param>
        public MemberSpaceController(ISettingService iSettingService, ITokenGradeService iTokenGradeService, 
                                     IMerchantService iMerchantService,IComponentContext icomponentContext) {
            _iSettingService = iSettingService;
            _iTokenGradeService = iTokenGradeService;
            _iMerchantService = iMerchantService;
            _iComponentContext = icomponentContext;
        }

        /// <summary>
        /// 升级创客会员
        /// </summary>
        /// <returns></returns>
        public ActionResult UpgradeTokenMaker(string wxOpenId) {
            var merchant = _iMerchantService.Get(UserId);
            ViewBag.WXOpenId = wxOpenId;
            ViewBag.Merchant = merchant;
            return View();
        }

        /// <summary>
        /// 升级为创客会员发起支付
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UpgradeTokenMakerPay(upgrade_token_maker_to_pay_model model) {
            setting_dto setting = _iSettingService.Get();
            var curMechant = _iMerchantService.Get(UserId);
            if ((int)curMechant.usertype >= (int)UserType.tokenMaker)
                throw new ServerErrorException("已报名，请勿重复操作");
            var tokenGrade = _iTokenGradeService.Get(UserType.tokenMaker);
            if (tokenGrade == null) throw new ServerErrorException(string.Format("{0} 级别信息未配置", UserType.tokenMaker.ToDescription()));
            var data = new native_model() {
                type = 2,
                pay_channel = PayChannel.H5Pay,
                body = "购买课程",
                tran_amount =  (tokenGrade.upfee * 100).ToString("0.##"),
                notify = setting.site.api_url + t_RequestMethod.TOKEN_USER_UPGRADE_NOTIFY,
                front_notify = string.Format("{0}/MemberSpace/UpgradeTokenMaker", t_RequestMethod.token_url),
                merchant_no = t_RequestMethod.merchant_no,
                method = t_RequestMethod.TOKEN_USER_UPGRADE_PAY,
                nonce = DtoHelper.RandCode(10),
                order_no = "OU" + DtoHelper.GenerateOrderNumber(),
                pay_code = "H5Pay",
                settle_type = "T1",
                openid = !string.IsNullOrEmpty(model.wx_open_id) ? model.wx_open_id : GetHostAddress(),
                is_wx_pub_account_pay = !string.IsNullOrEmpty(model.wx_open_id) ? true : false,
                bind_no = curMechant.merchant_no
            };
            //var binds = UpGradeFade.CalcMallProfits(_iComponentContext, UserId, UserType.tokenMaker);
            //data.binds.AddRange(binds);
            var result = await HChannelApi.Current.PostApi<native_h5_result>(data);
            if (result == null) {
                throw new ServerErrorException("网络异常");
            }

            var api_result = new ApiResultMessage { result_msg = "操作成功" };
            if (result.result_code == 1000) {
                if (data.is_wx_pub_account_pay) {//公众号支付
                    api_result.result_msg = result.pay_info;
                } else {
                    api_result.result_msg = result.code_url;
                }
                api_result.result_code = 1000;
            } else {
                throw new ServerErrorException(result.result_msg);
            }
            return Json(api_result, JsonRequestBehavior.AllowGet);
        }
    }
}